using System.Buffers.Text;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityGLTF;
using UnityGLTF.Loader;
using UnityGLTF.Timeline;


public class test : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void BinFileDownloader(string dataStr, string fileName, string contentType);

    public GameObject targetObject;
    public string dirPath;
    private ExportContext _context;
    private Scene scene;
    private GameObject[] arr = new GameObject[0];

    private void Awake()
    {
        _context = new ExportContext();
        scene = SceneManager.GetActiveScene();
#if UNITY_EDITOR
        dirPath = Application.dataPath.Replace("Assets", $"test");
#else
        dirPath = Application.dataPath;

#endif
        Ref();
    }

    private void OnGUI()
    {
        GUILayout.Label(dirPath);
        GUILayout.BeginHorizontal();
        GUILayout.Label("shader:");
        shaderName = GUILayout.TextField(shaderName, GUILayout.Width(200));
        GUILayout.Label("dir:");
        dirPath = GUILayout.TextField(dirPath, GUILayout.Width(500));
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        GUILayout.Label("filename:");
        if (filename.EndsWith(".glb"))
        {
            filename = GUILayout.TextField(filename, GUILayout.Width(500));
        }
        else
        {
            filename = GUILayout.TextField(filename + ".glb", GUILayout.Width(500));
        }

        GUILayout.EndHorizontal();


        if (GUILayout.Button("export"))
        {
            var go = Converto(targetObject);
            GLTFSceneExporter exporter = new GLTFSceneExporter(go.transform, _context);
            byte[] data = exporter.SaveGLBToByteArray(targetObject.name);

            GameObject.DestroyImmediate(go);
#if UNITY_WEBGL && !UNITY_EDITOR
            var base64Data = System.Convert.ToBase64String(data);
            BinFileDownloader(base64Data, filename, "application/octet-stream");
#else
            File.WriteAllBytes($"{dirPath}/{filename}", data);
            Debug.Log(data.Length);
#endif
        }

        if (GUILayout.Button("load"))
        {
#if UNITY_WEBGL
            StartCoroutine(loadByWeb());
#else
            StartCoroutine(load());
#endif
        }

        if (GUILayout.Button("Ref"))
        {
            Ref();
        }

        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i].tag.Equals("MainCamera")) continue;
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("select"))
            {
                filename = arr[i].name;
                targetObject = arr[i];
            }

            GUILayout.Label(arr[i].name);
            if (GUILayout.Button("del"))
            {
                GameObject.DestroyImmediate(arr[i]);
                Ref();
                break;
            }

            GUILayout.EndHorizontal();
        }
    }

    public string shaderName = "UnityGLTF/PBRGraph";

    GameObject Converto(GameObject go)
    {
        GameObject _go = GameObject.Instantiate(go);
        _go.name = go.name;
        var renders = _go.GetComponentsInChildren<Renderer>();
        for (int i = 0; i < renders.Length; i++)
        {
            renders[i].sharedMaterial.shader = Shader.Find(shaderName);
        }

        return _go;
    }

    void Ref()
    {
        arr = scene.GetRootGameObjects();
    }

    IEnumerator load()
    {
        var importOpt = new ImportOptions();
        importOpt.DataLoader = new UnityWebRequestLoader(dirPath);
        var import = new GLTFSceneImporter(filename, importOpt);
        yield return import.LoadScene();
        // import.LoadSceneAsync();.
        Ref();
    }

    string filename = "AntiqueCamera.glb";

    IEnumerator loadByWeb()
    {
        var importOpt = new ImportOptions();
        importOpt.DataLoader = new UnityWebRequestLoader(dirPath);
        var import = new GLTFSceneImporter(filename, importOpt);
        yield return import.LoadScene();
        Ref();
    }
}